package net.xdclass.video.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import net.xdclass.video.common.Result;
import net.xdclass.video.entity.Admin;
import net.xdclass.video.entity.domain.Comments;
import net.xdclass.video.entity.domain.Document;
import net.xdclass.video.mapper.CommentsMapper;
import net.xdclass.video.mapper.DocumentMapper;
import net.xdclass.video.service.CommentsService;
import net.xdclass.video.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@RestController
public class DocumentController {
    @Autowired
    private CommentsService commentsService;

    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private DocumentService documentService;

    @Autowired
    private DocumentMapper documentMapper;

    private final Path rootLocation = Paths.get("src/main/resources/static/files/document");

    @PostMapping("/api/document/save")
    public Result save(@RequestBody Document document){
        documentService.saveOrUpdate(document);
        return Result.success();
    }
    //使用了 @RequestParam 注解来声明方法的参数，用于从请求中获取对应的参数值。
    @GetMapping("/api/document/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        //QueryWrapper 来构建查询条件，并基于条件执行了分页查询
        QueryWrapper<Document> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        Page<Document> page = documentService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    @GetMapping("/apiOne/document")
    public  Result findAll(@RequestParam String name){
        QueryWrapper<Document> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        List<Document> commentsList=documentMapper.selectList(queryWrapper);
        return Result.success(commentsList);
    }

    @DeleteMapping("/api/document/{id}")
    public Result deleteById(@PathVariable Integer id){
        documentService.removeById(id);
        return Result.success();
    }

    //批量删除
    @PostMapping("/api/document/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        documentService.removeByIds(ids);
        return Result.success();
    }

    @SneakyThrows
    @PostMapping("/apiOne/document/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file,Document document) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        if (!Files.exists(rootLocation)) {
            Files.createDirectories(rootLocation);
        }
        try {
            Files.copy(file.getInputStream(), this.rootLocation.resolve(filename));
            // 保存文件信息到数据库

            document.setName(filename);
            document.setUrl("http://localhost:9090/files/document/"+filename);
            documentService.saveOrUpdate(document);
            // saveFileMetadata(filename, "uploads/" + filename);
            return ResponseEntity.ok("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败");
        }
    }

    /**
     * 导出接口
     */
    @GetMapping("/apiOne/document/export")
    public void exportExistingExcel(HttpServletResponse response,@RequestParam("name") String name) throws Exception {
        // 设定你的Excel文件路径
        String filePath = "src/main/resources/static/files/document/"+name;

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 对文件名进行URL编码，确保特殊字符不会导致问题
        name = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        // 读取文件并写入响应
        try (FileInputStream inputStream = new FileInputStream(filePath);
             ServletOutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}
